﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;

namespace AricentTestProject.controls
{
    public partial class LoginCtrl : BaseControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginErr.Text = "";

            if (User != null)
            {
                var user = User;
                User.LastActivity = DateTime.Now;
                User = user;
            }
        }

        protected void onLoginClick(object sender, EventArgs e)
        {
            var user = UserExtensions.getByLoginPassword(LoginBox.Text, PassBox.Text);
            if (user == null)
            {
                LoginErr.Text = "Auth failed. User not found";
                return;
            }

            if (user.SessionId == Session.SessionID)
            {
                User = user;
            }
            else
            {
                if (string.IsNullOrEmpty(user.IP) || user.IP.Equals(UserIP))
                {
                    User = user;
                }
                else
                {
                    TimeSpan ts = DateTime.Now - (DateTime)user.LastActivity;
                    if (ts.TotalMinutes > GlobalSettings.SessionTimeOut)
                    {
                        User = user;
                    }
                    else
                    {
                        LoginErr.Text = "You already logged";
                    }
                }                
            }

        }
    }
}